package com.pat.web.controller;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.pat.common.Constants;
import com.pat.web.ApiResponse;
import com.pat.web.NoNeedLogon;
import com.pat.web.model.Adopt;
import com.pat.web.model.AdoptComment;
import com.pat.web.model.Focus;

public class AdoptController extends Controller{
	private static final int PAGESIZE = 20;

	//领养救助列表
	@NoNeedLogon
	public void getAdoptList(){
		Integer pageIndex = getParaToInt("pageIndex");
		if (pageIndex == null || pageIndex < 1) {
			pageIndex = 1;
		}
		Integer pageSize = getParaToInt("pageSize");
		if (pageSize == null) {
			pageSize = PAGESIZE;
		}
		
		Long userId = getAttr(Constants.LOGIN_USER_ID);
		String selectSql = null;
		
		String sqlExceptSelect = null;
		if (userId != null) {
			selectSql = "select a.* ,(select count(1) from adopt b where  a.category_id = b.category_id) as total, f.focus_content_id ";
			sqlExceptSelect = "from adopt a left join focus f on  a.id = f.focus_content_id and f.focus_type = 1 and f.user_id = " + userId
					+ " where 1 = 1 ";
		}else{
			selectSql = "select a.* ,(select count(1) from adopt b where  a.category_id = b.category_id) as total ";
			sqlExceptSelect = "from adopt a where 1 = 1 ";
		}
		Integer categoryId  = getParaToInt("categoryId");
		Integer countyId  = getParaToInt("countyId");
		Integer cityId  = getParaToInt("cityId");
		Integer provinceId  = getParaToInt("provinceId");
		
		if(categoryId != null){
			sqlExceptSelect = sqlExceptSelect + "and a.category_id = " + categoryId;
		}
		
		if(countyId != null){
			sqlExceptSelect = sqlExceptSelect + " and a.county_id = " + countyId;
		}
		
		if(cityId != null){
			sqlExceptSelect = sqlExceptSelect + " and a.city_id = " + cityId;
		}
		
		if(provinceId != null){
			sqlExceptSelect = sqlExceptSelect + " and a.province_id = " + provinceId;
		}
		
		sqlExceptSelect = sqlExceptSelect + " order by a.create_time desc";
		ApiResponse response = new ApiResponse();
		response.setStatusCode("0000");
		
		Page<Record> records =  Db.paginate(pageIndex, pageSize,selectSql,sqlExceptSelect);
		response.setData(records);
		render(new JsonRender(response));
	}
	
	@NoNeedLogon
	public void  getAdoptDetailById(){
		ApiResponse response = new ApiResponse();
		Long id = getParaToLong("id");
		Adopt adopt = Adopt.dao.findFirst("select * from adopt where id =?",id);
		
		if (adopt == null) {
			response.setStatusCode("00001");
			response.setErrorMessage("参数错误，未找到领养救助信息");
		}else {
			List<Record> commentRecords = Db.find("select a.* "
					+ "from adopt_comment a where a.adopt_id = ? ", id);
			
			if (CollectionUtils.isNotEmpty(commentRecords)) {
				for (Record record : commentRecords) {//组装评论用户信息以及用户宠物信息
					Record userInfo =  Db.findFirst("select u.nick_name,u.photo, p.*, pc.category_name from  user u, pet p, pet_category pc  where  pc.id = p.pet_category_id and p.user_id = u.id and u.id = ? order by p.create_time limit 1", record.getLong("user_id"));
					record.set("userInfo", userInfo);
					if (record.getLong("reply_comment_id") != null) {
						Record repliedCommentInfo = Db.findFirst("select a.*, u.nick_name from adopt_comment a, user u where u.id = a.user_id and a.id = ? ",record.getLong("reply_comment_id"));
						record.set("repliedCommentInfo", repliedCommentInfo);
					}
				}
			}
			
			adopt.put("commentInfo",commentRecords);
			response.setStatusCode("0000");

		}
		
		response.setData(adopt);
		render(new JsonRender(response));
	}
	
	public void createAdopt() {
		Adopt adopt = getBean(Adopt.class, "");
		adopt.setUserId(getAttr(Constants.LOGIN_USER_ID));
		adopt.setCreateTime(new Date()).save();
		ApiResponse response = new ApiResponse();
		response.setData(adopt.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}

	public void focus() {
		Long userId =  getAttr(Constants.LOGIN_USER_ID);
		Integer operateType = getParaToInt("operateType");
		Focus focus = getBean(Focus.class, "");
		Focus record = Focus.dao.findFirst("select * from focus where focus_type = ? and user_id =? and focus_content_id = ?", focus.getFocusType(),userId,focus.getFocusContentId());
		ApiResponse response = new ApiResponse();

		if (record != null ) {
			if(operateType != null && operateType == 1){
				response.setStatusCode("00001");
				response.setErrorMessage("已经收藏过了");
				renderJson(response);
			}else {
				if (record.delete()) {
					Adopt adopt = Adopt.dao.findById(focus.getFocusContentId());
					if (adopt != null) {
						adopt.setUpdateTime(new Date());
						adopt.setCollectionNum(adopt.getCollectionNum() - 1);
						adopt.update();
					}
					response.setStatusCode("0000");
					response.setData(adopt.getCollectionNum());
					renderJson(response);
				}else{
					response.setStatusCode("00003");
					response.setErrorMessage("取消收藏失败 ");
					renderJson(response);
				}
			}
		}else{
			if(operateType != null && operateType == 1){
				focus.setUserId(userId);
				focus.setCreateTime(new Date());
				focus.setStatus(1L);

				if (focus.save()) {
					Adopt adopt = Adopt.dao.findById(focus.getFocusContentId());
					if (adopt != null) {
						adopt.setUpdateTime(new Date());
						adopt.setCollectionNum(adopt.getCollectionNum() + 1);
						adopt.update();
						response.setData(adopt.getCollectionNum());
					}
				}
				response.setStatusCode("0000");
				renderJson(response);
			}else{
				response.setStatusCode("00003");
				response.setErrorMessage("取消收藏失败 ");
				renderJson(response);
			}
		}
		
	}
	
	//发表评论
	public void adoptComment() {
		AdoptComment adoptComment = getBean(AdoptComment.class, "");
		adoptComment.setUserId(getAttr(Constants.LOGIN_USER_ID));
		adoptComment.setCreateTime(new Date()).save();
		ApiResponse response = new ApiResponse();
		response.setData(adoptComment.getId());
		response.setStatusCode("0000");
		renderJson(response);
	}
	
}
